package 面试.ref;/*
 *@Author: helen
 *@Date:   2021/4/16 14:59
 *@Description:
 */

import java.lang.ref.SoftReference;

public class SoftReferenceDemo {
    //内存够用就不回收，不够用就回收
    public static void SoftRef_Memory_Enough(){
        Object o1 = new Object();
        SoftReference<Object> softReference = new SoftReference<>(o1);
        System.out.println(o1);
        System.out.println(softReference.get());

        o1 = null;
        System.gc();

        System.out.println(o1);
        System.out.println(softReference.get());
    }

    /**
     * 故意产生大对象，让JVM产生OOM，查看软引用回收情况
     * -Xms5m -Xmx5m -XX:+PrintGCDetails
     */
    public static void SoftRef_Memory_NotEnough(){
        Object o1 = new Object();
        SoftReference<Object> softReference = new SoftReference<>(o1);
        System.out.println(o1);
        System.out.println(softReference.get());

        o1 = null;

        try{
            byte[] bytes = new byte[30*1024*1024];//用了30m
        }catch (Exception e){
            e.printStackTrace();
         }finally {
            System.out.println(o1);
            System.out.println(softReference.get());
        }
    }

    public static void main(String[] args) {
        //SoftRef_Memory_Enough();
        SoftRef_Memory_NotEnough();
    }
}
